// pages/join/index.js
var userInfo = wx.getStorageSync('userInfo');
var url = getApp().globalData.ApiUrl;
var timeformat = require('../../utils/timeformat.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: userInfo.avatar,
    goods_details: {}, //商品详情
    kanjia_info: {}, //拼团详情
    hr: '',   //小时
    min: '', //分钟
    sec: '', //秒钟
    kan_btn: true, //帮忙砍价
    out_date: false, //是否过期
    order_id: 0,
  },
  /** 
   * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
   * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
   * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
   * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
   */
  count_down: function (allsec) {
    var that = this;
    clearTimeout(that.data.timer);
    that.setData({
      day: timeformat.timeformat(allsec).days + '天',
      hr: timeformat.timeformat(allsec).hrs,
      min: timeformat.timeformat(allsec).mins,
      sec: timeformat.timeformat(allsec).second
    });
    if (allsec <= 0) {
      that.setData({
        day: '0天',
        hr: '00',
        min: '00',
        sec: '00'
      });
      // timeout则跳出递归
      return;
    };
    that.data.timer = setTimeout(function () {
      // 放在最后--
      allsec -= 1000;
      that.count_down(allsec);
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    var that = this;
    var key = wx.getStorageSync('key');
    if (!key){
      wx.navigateTo({
        url: '/pages/authorize/index',
      });
    };
    if (options.kanjia_id) {
      that.setData({
        kanjia_id: options.kanjia_id,
      })
    };
    if (options.pay_sn) {
      that.setData({
        pay_sn: options.pay_sn
      })
    };
    that.setData({
      order_id: options.order_id,
      goods_id: options.goods_id,
    })    
    wx.showLoading({
      title: '加载中，请稍后...',
    })
    // var kanjia_info = JSON.parse(options.kanjia_info);
    var that = this;
    var data = {
      key: key,
      buyer_id: options.buyer_id,
    };
    if (options.pay_sn) {
      data.pay_sn = options.pay_sn;
    };
    if (options.kanjia_id) {
      data.kanjia_id = options.kanjia_id;
    }
    wx.request({
      url: url + '/mobile/index.php?act=kanjia&op=info',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: data,
      success: function (res){
        if(res.data.code == 200){
          wx.hideLoading();
          if (res.data.datas.kanjia_info.now >= res.data.datas.kanjia_info.min_num){
            that.setData({
              needLeave: false,
            });
            that.setData({
              goods_price: res.data.datas.kanjia_info.kanjia_price,
            })          
          }else{
            var price = [];
            var datas = res.data.datas.kanjia_info;
            for (var i in datas.kanjia_info.kan_price) {
              price.push(datas.kanjia_info.kan_price[i]);
            }
            console.log(price, typeof price);
            that.setData({
              needLeave: true,
              kanjia_info: datas,
              price: price
            });
            
            that.goodsDetails(that.data.goods_id);
            if (res.data.datas.kanjia_info.kanjia_end_time <=0){
              that.setData({
                out_date: true
              });
            }else{
              that.count_down(res.data.datas.kanjia_info.kanjia_end_time * 1000);
            }            
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });

    that.getMusicInfo();
  },
  /**
   * 获取商品详情
   */
  goodsDetails: function (goods_id){
    var that = this;
    //获取商品详情
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var imgURL = res.data.datas.goods_image.split(',');
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          var goods_spec = [];
          var spec_id = [];
          for (var spec_d in res.data.datas.goods_info.goods_spec) {
            goods_spec.push(res.data.datas.goods_info.goods_spec[spec_d]);  // 商品规格
            spec_id.push(spec_d);
            var spec = goods_spec.toString().replace(/,/g, " ");
          };
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp2.active = (j in res.data.datas.goods_info.goods_spec) ? true : false;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (spec) {
            this.setData({
              propertyChildNames: spec,
            })
          };
          if (datas.goods_info.kanjia_promotion == 1) {
            that.setData({
              imgUrl: imgURL,
              sum: imgURL.length,
              goods_details: res.data.datas,
              specALLArr: specALLArr,
              buyGoods_id: goods_id, //购买的商品id
              detailData: datas,  //商品详情
              goods_storage: datas.goods_info.goods_storage, //商品库存
              goods_price: datas.goods_info.kanjia_price,
            });
          } else {
            that.setData({
              imgUrl: imgURL,
              sum: imgURL.length,
              goods_details: res.data.datas,
              specALLArr: specALLArr,
              buyGoods_id: goods_id, //购买的商品id
              detailData: datas,  //商品详情
              goods_storage: datas.goods_info.goods_storage, //商品库存
              goods_price: datas.goods_info.goods_price,
            });
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    }); 
  },
  // 获取商城优惠列表
  getMusicInfo: function () {
    var that = this;
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_kanjia_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      success: (res) => {
        if (res.data.code == 200) {
          var goodsRecmd = res.data.datas;
          that.setData({
            goodsRecmd: goodsRecmd
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /**
   * 帮忙砍价
   */
  toJoinGroup: function (e){
    var key = wx.getStorageSync("key");
    if (!key) {
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }
    var order_id = e.currentTarget.dataset.order_id;
    var that = this; 
    wx.showLoading({
      title: '加载中，请稍后...',
    })
    wx.request({
      url: url + '/mobile/index.php?act=kanjia&op=kanjia',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'get',
      data: {
        key: key,
        order_id: that.data.order_id,
      },
      success: function (res){
        if (res.data.code == 200){
          wx.hideLoading();
          wx.showToast({
            title: '帮好友砍价成功',
            icon: 'none',
            duration: 2000,
            mask: true
          });
          that.setData({
            kan_btn: false,
            resinfo: res.data.datas.msg
          });
        }else{
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          };
          wx.showToast({
            title: res.data.datas.error.msg,
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  /**
   * 跳转商品详情
   */
  toDetailTap: function (e) {
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + goods_id,
    });
  },
  /**
   * 我要砍
   */
  toBargain: function (e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var goods_img = e.currentTarget.dataset.goods_img;
    that.setData({
      showView: true,
      goods_img: goods_img
    });
    that.goodsDetails(dataset.goods_id);
  },
  /**
   * 切换规格选中状态
   * @author chelfinn
   * @date 2018-09-18
   */
  clickTap: function (e) {
    var that = this;
    var specALLArr = that.data.specALLArr;
    var childs = that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData;
    // 取消该分类下的子栏目所有的选中状态
    for (var i = 0; i < childs.length; i++) {
      that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[i].active = false;
    }
    // 设置当前选中状态
    that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[e.currentTarget.dataset.propertychildindex].active = true;
    that.setData({
      specALLArr: specALLArr
    });
    // 循环数组 获取点中状态时的规格
    for (var id in specALLArr) {
      for (var i in specALLArr[id].twoData) {
        if (specALLArr[id].twoData[i].active == true) {
          ids.push(specALLArr[id].twoData[i].id);  // 获取的商品选中时的id
          valus.push(specALLArr[id].twoData[i].name);   // 获取商品点中时的规格
        }
      };
    };
    var spec_id = ids.sort().join("|");   // 升序
    var spec_value = valus.toString().replace(/,/g, " ");  // 选中的规格
    var spec_list = that.data.detailData.spec_list;
    if (spec_value) {
      this.setData({
        propertyChildNames: spec_value,
      })
    }
    if (spec_id in spec_list) {
      that.setData({
        buyGoods_id: spec_list[spec_id], //获取购买的商品id
      });
    }
  },
  /**
   * 立即购买
   */
  groupBuyNow: function (e) {
    var that = this;
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    if (e.currentTarget.dataset.is_kanjia == 1) {
      var is_kanjia = 1;
    };
    var ifcart = '';
    var log_id = '';
    var goods_id = e.currentTarget.dataset.goods_id;
    //item 店铺名，商品名，商品图片，选中规格，商品单价，数量
    var item = {};
    item.store_name = that.data.goods_details.store_info.store_name;
    item.store_id = that.data.goods_details.store_info.store_id;
    item.goods_name = that.data.goods_details.goods_info.goods_name;
    item.goods_price = that.data.goods_price;
    item.spec_name = that.data.propertyChildNames;
    item.goods_num = that.data.num;
    item = JSON.stringify(item);
    var totalPrice = that.data.goods_price;
    var cart_id = goods_id + '|1';

    var item1 = JSON.parse(item);
    var storega = that.data.goods_storage;
    if (item1.spec_name) {
      var arr = item1.spec_name.split(" ");
    };
    if (this.data.specALLArr.length == 0) {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_kanjia=' + is_kanjia,
      });
    } else {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      if (arr.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格尺寸哟~',
          showCancel: false,
        })
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_kanjia=' + is_kanjia,
      });
    }
  },
  /**
   * 关闭弹窗
   */
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
      num: 1,
    });
  },
  toIndex: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})